package com.zx.yixun.net;


import android.net.ParseException;
import android.util.Log;
import com.google.gson.JsonSyntaxException;
import com.zx.ymy.net.ResponseException;

import org.json.JSONException;
import org.json.JSONObject;
import retrofit2.HttpException;

import java.io.IOException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

/**
 * 异常处理
 */
public class RxExceptionUtil {
    public static String exceptionHandler(Throwable e,String msg) {
        String errorMsg = "网络异常";
        if (e instanceof UnknownHostException) {
            errorMsg = "网络不可用";
        } else if (e instanceof SocketTimeoutException) {
            errorMsg = "请求网络超时";
        } else if (e instanceof HttpException) {
            HttpException httpException = (HttpException) e;
            errorMsg = convertStatusCode(httpException,msg);
        } else if (e instanceof ParseException || e instanceof JSONException || e instanceof JsonSyntaxException) {
            errorMsg = "数据解析错误";
        } else if(e instanceof ResponseException) {
            errorMsg = e.getMessage();
        }
        return errorMsg;
    }

    private static String convertStatusCode(HttpException httpException,String msgError) {
        String msg;
        if (httpException.code() >= 500 && httpException.code() < 600) {
//            msg = "服务器处理出错 code"+httpException.code();
            msg = "服务请求出了点小问题";
            if (httpException.code() == 500) {
                try {
                    String content = httpException.response().errorBody().string();
                    JSONObject jsonObj = new JSONObject(content);
                    msg = jsonObj.getString("msg");
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (JSONException ignored){

                } catch (NullPointerException ignored) {

                }
            }
        } else if (httpException.code() == 422) {
            try {
                String responseString = httpException.response().errorBody().string();
                JSONObject jsonObject = new JSONObject(responseString);
                msg = jsonObject.getString("msg");
            } catch (Exception e) {
                e.printStackTrace();
                msg = "服务器无法处理请求";
            }
        } else if (httpException.code() >= 400 &&httpException.code()<422&&httpException.code()>422&& httpException.code() < 500) {
            msg = "服务器无法处理请求";
        } else if (httpException.code() >= 300 && httpException.code() < 400) {
            msg = "请求被重定向到其他页面";
        } else {
            msg = httpException.message();
        }
        return msg;
    }
}












